package com.example.testtransition;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Looper;
import android.os.PowerManager;
import android.os.Process;
import android.text.TextUtils;
import android.view.Display;
import android.view.WindowManager;

import androidx.annotation.IntRange;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

//import com.yidui.base.log.Logger;
//import com.yidui.common.utils.TextUtils;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class AppUtils {

    public static String processName;
    private static final String TAG = "AppUtilsBase";


    public static boolean isMainProc(Context context) {
        if (context == null) {
//            Logger.d(TAG, "isMainProc :: context is null");
            return false;
        }
        String processName = getProcessName(Process.myPid());
        String packageName = context.getPackageName();
        return android.text.TextUtils.equals(processName, packageName);
    }

    public static boolean inMainProcess(Context context) {
        String packageName = context.getPackageName();
        if (android.text.TextUtils.isEmpty(processName)) {
            processName = getProcessName(context, 1);
        }
        return android.text.TextUtils.equals(packageName, processName);
    }

    public static boolean inMainThread() {
        try {
            return Looper.getMainLooper().getThread().getId() == Thread.currentThread().getId();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * 当前activity 是否已经销毁
     *
     * @param context
     * @return
     */
    public static boolean contextExist(Context context) {
        if (context == null) {
            return false;
        }
        if ((context instanceof Activity)) {
            Activity activity = ((Activity) context);
            if (activity.isFinishing()) {
                return false;
            }
            if (Build.VERSION.SDK_INT >= 17) {
                return !activity.isDestroyed();
            }
        }
        return true;
    }



    /**
     * 当前activity 是否已经销毁
     *
     * @param context
     * @return
     */
    public static boolean contextExistFixSingleTeamMoreMemAdapter(Context context) {
        if (context == null) {
            return false;
        }

        Context ctx;
        // Dialog的context是ContextWrapper
        // ContextWrapper的baseContext是Activity
        if (context instanceof ContextWrapper) {
            ctx = ((ContextWrapper) context).getBaseContext();
        } else {
            ctx = context;
        }

        if (ctx instanceof Activity) {
            Activity activity = ((Activity) ctx);
            if (activity.isFinishing()) {
                return false;
            }
            if (Build.VERSION.SDK_INT >= 17) {
                return !activity.isDestroyed();
            }
        }
        return true;
    }



    public static boolean fragmentExist(Fragment fragment) {
        if (fragment == null) {
            return false;
        }
        if (fragment.getActivity() == null || fragment.getActivity().isFinishing()) {
            return false;
        }
        if (Build.VERSION.SDK_INT >= 17) {
            return !fragment.getActivity().isDestroyed();
        }
        return true;
    }



    /**
     * 判断当前是否为锁屏状态
     *
     * @param context Android Context
     * @return 是否为锁屏
     */
    public static boolean isScreenOn(Context context) {
        if (Build.VERSION.SDK_INT < 20) {
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            return !pm.isScreenOn();
        } else {
            WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            return wm.getDefaultDisplay().getState() == Display.STATE_OFF;
        }
    }

    /**
     * 获取当前进程名
     *
     * @param context
     * @return 进程名
     */
    private static String getProcessName(Context context, int tryTimes) {
        String processName = null;

//        try {
        // ActivityManager
        ActivityManager am = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE));

        int pid = Process.myPid();
//            int tryTimes = 0;
//            while (true) {
        List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = am.getRunningAppProcesses();
        if (runningAppProcesses != null && runningAppProcesses.size() > 0) {
            for (ActivityManager.RunningAppProcessInfo info : runningAppProcesses) {
                if (info.pid == pid) {
                    processName = info.processName;
                    break;
                }
            }
        }

        // go home
        if (TextUtils.isEmpty(processName)) {
            if (tryTimes > 3) {
                return context.getPackageName();
            }
            return getProcessName(context, ++tryTimes);
        } else {
            return processName;
        }

//                tryTimes += 1;
//                // take a rest and again
//                if (tryTimes < 48) {
//                    try {
//                        Thread.sleep(100L);
//                    } catch (Exception ex) {
//                        ex.printStackTrace();
//                        break;
//                    }
//                } else {
//                    break;
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return context.getPackageName();
    }

    public static String getCurrentProcessName() {
        return getProcessName(Process.myPid());
    }

    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    public static String getProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return null;
    }



    //kill process
    public static void killProcess(Context context) {
        // ActivityManager
        try {
            List<Integer> pids = new ArrayList<>();
            ActivityManager am = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE));
            List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = am.getRunningAppProcesses();
            if (runningAppProcesses != null && runningAppProcesses.size() > 0) {
                for (ActivityManager.RunningAppProcessInfo info : runningAppProcesses) {
                    if (info.processName.startsWith(context.getPackageName())) {
                        pids.add(info.pid);
                    }
                }
            }
            for (int pid : pids) {
                Process.killProcess(pid);
                Process.sendSignal(pid, Process.SIGNAL_KILL);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 检查权限集合
     *
     * @param activity
     * @param permissions
     * @param requestCode
     * @return
     */
    public static boolean checkSelfPermissions(@NonNull Activity activity, @NonNull String[] permissions, @IntRange(from = 0) int requestCode) {
        List<String> deniedPermissions = new ArrayList<>();

        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(activity, permission)
                    != PackageManager.PERMISSION_GRANTED) {
//                Logger.w(TAG, "checkSelfPermissions :: denied permission = " + permission);
                deniedPermissions.add(permission);
            }
        }

        if (deniedPermissions.size() > 0) {
            String[] permissionsStr = new String[deniedPermissions.size()];
            for (int i = 0; i < deniedPermissions.size(); i++) {
                permissionsStr[i] = deniedPermissions.get(i);
//                Logger.w(TAG, "checkSelfPermissions :: permissionsStr[" + i + "] = " + permissionsStr[i]);
            }
            ActivityCompat.requestPermissions(activity, permissionsStr, requestCode);
            return false;
        }
        return true;
    }


    /**
     * 是否拥有所有权限
     */
    public static boolean hasAllPermissions(Context context, String[] permissions) {
        List<String> deniedPermissions = new ArrayList<>();

        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(context, permission)
                    != PackageManager.PERMISSION_GRANTED) {
//                Logger.i(TAG, "checkSelfPermissions :: denied permission = " + permission);
                deniedPermissions.add(permission);
            }
        }

        return deniedPermissions.size() == 0;
    }

    /**
     * 获取状态栏高度
     *
     * @param context
     * @return
     */
    public static int getStatusBarHeight(Context context) {
        Class<?> c = null;
        Object obj = null;
        Field field = null;
        int x = 0, statusBarHeight = 20;
        try {
            c = Class.forName("com.android.internal.R$dimen");
            obj = c.newInstance();
            field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(obj).toString());
            statusBarHeight = context.getResources().getDimensionPixelSize(x);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return statusBarHeight;
    }





}
